import base64
from io import BytesIO

import qrcode
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views.decorators.cache import cache_control, cache_page, never_cache


# @cache_control(max_age=7 * 24 * 60 * 60)
@never_cache
def web_login(request):
    rec_data = request.GET
    if 'phone' in rec_data and 'pass' in rec_data and 'redir' in rec_data:
        redir = rec_data['redir']
        if redir == 'channel':
            res_data = channel(request)
        else:
            res_data = render(request, rec_data['redir'].lower() + '.html', {'phone': rec_data['phone'], 'pass': rec_data['pass']})
    else:
        res_data = HttpResponse('attrs error')
    return res_data


@never_cache
def channel(request):
    rec_data = request.GET
    id = rec_data.get('phone')
    name = rec_data.get('name')
    code = generate_qrcode('http://wx.zgtxcj.com/gongzhonghao/zhuce.php?id={}&name={}'.format(id, name))
    content = {'code': code}
    return render(request, 'channel.html', content)


def generate_qrcode(data):
    """二维码"""
    img = qrcode.make(data)
    buf = BytesIO()
    img.save(buf)
    image_stream = buf.getvalue()
    return base64.b64encode(image_stream).decode('utf-8')
